<?php
require (APPLICATION_PATH . "/../webnews/nntp.php");
class Default_Model_NewsServer
{

    public $Id;
    public $Yenc;
    public $GroupName;
    public $NNTP;
    public $groups;

    function __construct($NoLoad=NULL)
    {
        $info = array ('server'   => "news.usenet.net",
                        'username' => 'info@cyber8.net',
                        'password' => 'Password');
        $Server     = $info['server'];
        $Username   = $info['username'];
        $Password   = $info['password'];
        $Db         = array(); 
        $this->NNTP = new NNTP($Server, trim($Username), trim($Password));   


        if (!$NoLoad) $this->GetGroups();
    } 
    
    function GetGroupInfo ($groupname)
    {  
        if (!$this->NNTP->connect())                                                
        {                                                
            echo "Unable to connect!";                                             
            return false;                                               
        }  
	if ( ! ( $gi=$this->NNTP->join_group(trim($groupname)) ) )                    
	{
	    echo "Unable to join group [$groupname]";  
	    $this->Disconnect();
	    return false;
	}   
	$this->Disconnect();
        return $gi; 
    } 
    
    function Connect2Group ()
    {      
        if (!$this->NNTP->connect())                                                
        {                                                
            echo "Unable to connect!";                                             
            return false;                                               
        }  
        
	if ( ! ( $gi=$this->NNTP->join_group(trim($this->GroupName)) ) )                    
	{
	    echo "Unable to join group [$this->GroupName]";  
	    $this->Disconnect();
	    return false;
	}   
        return $gi;
    }
    
    function Disconnect()
    {
        $this->NNTP->quit();
    } 

    function GetGroups($Param=NULL)
    {
        $Profile   = new Default_Model_UserProfile; 
        $DATA_URI  = DATA_PATH . "/server-groups-list.ini";
        $groupList = simplexml_load_file($DATA_URI);
        $query     = $Param ? "//group[contains(@name,'{$Param}')]" : "//group";
        $result = $groupList->xpath($query); 
        $this->groups = array();
        for($x=0;$x<sizeof($result);$x++)
        { 
             $group = new Default_Model_Newsgroup($result[$x]);
             $group->Subscribed = $Profile->IsSubscribed($group->Name) ? true : false;
             $this->groups[$group->Name] = $group;
        }
        uasort ($this->groups, 'gcmp');
    }


    function DownloadArticles ($id = '', $groupname = '')
    {       
        if (strlen($id) > 0) $this->Id = $id;
        $this->GroupName =  $groupname;
        $messages = array();
        $ids      = explode ('-', $this->Id);    
        $this->Connect2Group();
        
	for ($i=0;$i<sizeof($ids);$i++)
	{
            $message = $this->NNTP->get_article($ids[$i]);    
            $messages[] = $message;
	} 
        
        $this->Disconnect();
        
        return $this->Assemble($messages);
    }


    function Assemble ($messages)
    {
        $content = array();        
		for ($i=0;$i<sizeof($messages);$i++)     
		{             
		    $MIME_Message = $messages[$i];
		    if (!$MIME_Message)
		    {
		        continue;
		    }
            $header = $MIME_Message->get_main_header();                                               
            $parts  = $MIME_Message->get_all_parts();                                                                
            $count  = 0;   
            $this->Yenc   = false;                                       
            foreach ($parts as $part)                                              
            {              
                $subject = isset($part["header"]["subject"]) ? $part["header"]["subject"] : "";    
                if (isset($part['header']['content-transfer-encoding']) && 
                    strlen($part['header']['content-transfer-encoding']) > 0)
                {
                    $this->Encoding = $part['header']['content-transfer-encoding'];  
                }                                              
                $body    = $part["body"];                                              
                if ( (strpos($body, "ybegin") !== false) || (strpos(strtolower($subject), "yenc") !== false) )                                             
                { // YENC decoding  
                    $arr = array ();                                             
                    $arr["header"]     = array ("content-type"=>"image/jpeg", "content-transfer-encoding" => "yenc");                                             
                    $arr["body"]       = $part["body"];   
                    $this->Yenc      = true;                            
                }                                               
                $attachment_id = $count;                                           
                $count++;                                              
            }                                               

                                                        
            if ($MIME_Message->get_total_part() > $attachment_id)                                              
            {                                             
                $header = $MIME_Message->get_part_header($attachment_id);                                             
                $body   = $MIME_Message->get_part_body($attachment_id);                                             
                if (strcmp($header["content-type"],"") == 0)                                              
                {                                             
                    header("Content-Type: text/html");                                             
                    echo $messages_ini["error"]["request_fail"];                                             
                }                                              
                else                                              
                {                          
                    $content[] = $MIME_Message->get_part($attachment_id);
                }                                             
            }                                              
            else                                              
            {                                             
                header("Content-Type: text/html");                                             
                echo $messages_ini["error"]["multipart_fail"];                                             
            }  
		}    
		return $content;
    }




    function LoadGroupsfromServer($queueKey=0)
    {
        $Db         = array();  
        $this->groups = array();
        if (!$this->NNTP->connect())                                                  
        {                                                                                                 
            header("Content-Error: " . $this->NNTP->get_error_message());                                                 
            echo $nntp_server."!<b>".$messages_ini["error"]["nntp_fail"]."</b><br>";                                                  
            echo "Error: " . $this->NNTP->get_error_message()."<br>";                                                  
        }                                                  
        else                                                 
        {                                                                
            $buf       = $this->NNTP->send_request("list active");                                                  
            $response  = $this->NNTP->parse_response($buf);                                                   
            $buf       = fgets($this->NNTP->nntp, 4096);                                                  
            $ret       = array();                                                  
                                                  
            while (strlen($buf) > 0)                                                  
            {                                                   
                if (trim($buf)==".")                                                 
                {                                                  
                    break;                                                 
                }                                                 
                $arr  = explode (" ", $buf);   
            
		if (preg_match('/alt\.binaries(.*)/',$arr[0]))                                             
		{ 	 
                    $numBegin  = $arr[1];
                    $numEnd    = $arr[2];
		    $groupname = htmlentities( str_replace("'","&apos;",$arr[0]) );     
                    $group = new Default_Model_Newsgroup;
                    $group->Name  = $groupname;
                    $group->MinID = min($numBegin, $numEnd);
                    $group->MaxID = max($numBegin, $numEnd);
                    $group->Size  = $group->MaxID - $group->MinID; #max($numBegin, $numEnd);

                    $this->groups[] = $group;
		}                                               
                $buf  = fgets($this->NNTP->nntp, 4096);    
            }                                                  
        }                                 
        $this->NNTP->quit();  
       
    }     
}

function gcmp ($a, $b) {
return strcmp ($a->Name, $b->Name) < 0 ? -1 : 1;
}





